package com.qf.controller;


import com.qf.pojo.Project;
import com.qf.pojo.WorkerOrder;
import com.qf.service.ProjectService;
import com.qf.service.WorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
@Controller
public class WorkController {

    @Autowired
    private ProjectService projectService;
    @Autowired
    private WorkOrderService workOrderService;

    @GetMapping("/index")
    public String index(Model model){
        List<Project> projectList = projectService.findAll();
        model.addAttribute("projectList",projectList );
        return "index";
    }

    @GetMapping("/add_ui")
    public String addUI(@RequestParam Long projectId,Model model){
        model.addAttribute("projectId",projectId );
        return "add";
    }


    @PostMapping("/add")
    public String add(@Validated WorkerOrder workerOrder, BindingResult result,
                      RedirectAttributes redirectAttributes){
            if (result.hasErrors()){
                String message = result.getFieldError().getDefaultMessage();
                redirectAttributes.addAttribute("addInfo", message+"参数不合法");
                redirectAttributes.addAttribute("projectId", workerOrder.getProjectId());
                return "redict:/add_ui";
            }
        Integer save = workOrderService.save(workerOrder);
            if (save==1){
                return "redirect:/list";
            }else {
                redirectAttributes.addAttribute("addInfo", "添加工单失败 请重新输入");
                redirectAttributes.addAttribute("projectId", workerOrder.getProjectId());
                return "redict:/add_ui";
            }

    }

    @GetMapping("/list")
    public String list(Model model){
        List<WorkerOrder> list = workOrderService.findWorkorderAndProjectName();
        model.addAttribute("list", list);
        return "list";
    }
}
